using System;
using System.Text.RegularExpressions;

namespace SecuBat.Crawling.Forms
{
	/// <summary>
	/// Summary description for FormParameter.
	/// </summary>
	public class FormParameter
	{
		private FormParameterType _type = FormParameterType.None;
		private String _name = "";
		private String _value = "";
		private const String _typeExpression = "type\\s*?=\\s*?([\"']?)([^\\1]*?)(\\1)([\\s>])";
		private const String _nameExpression = "name\\s*?=\\s*?([\"']?)([^\\1]*?)(\\1)([\\s>])";
		private const String _valueExpression = "value\\s*?=\\s*?([\"']?)([^\\1]*?)(\\1)([\\s>])";

		public string Name
		{
			get { return _name; }
			set { _name = value; }
		}

		public string Value
		{
			get { return _value; }
			set { _value = value; }
		}

		public FormParameterType Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public FormParameter(String htmlCode)
		{
			Regex typeRegex = new Regex(_typeExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			Match typeMatch = typeRegex.Match(htmlCode);
			if (typeMatch != null)
			{
				if (typeMatch.Value.Length > 0)
				{
					try
					{
						Type = (FormParameterType) Enum.Parse(typeof(FormParameterType), typeMatch.Groups[2].Value, true);
					}
					catch (Exception ex)
					{
						throw new InvalidTagException("The identified input tag \"" + htmlCode + "\" does not contain a valid type attribute!", ex);	
					}
				}
				else
				{
					throw new InvalidTagException("The identified input tag \"" + htmlCode + "\" does not contain a valid type attribute!");	
				}
			}
			else
			{
				throw new InvalidTagException("The identified input tag \"" + htmlCode + "\" does not contain a type attribute!");	
			}

			Regex nameRegex = new Regex(_nameExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			Match nameMatch = nameRegex.Match(htmlCode);
			if (nameMatch != null)
			{
				if (nameMatch.Value.Length > 0)
				{
					this.Name = nameMatch.Groups[2].Value;
				}
				else
				{
					if (this.Type != FormParameterType.Submit)
						throw new InvalidTagException("The identified input tag \"" + htmlCode + "\" does not contain a valid name attribute!");	
				}
			}
			else
			{
				if (this.Type != FormParameterType.Submit)
					throw new InvalidTagException("The identified input tag \"" + htmlCode + "\" does not contain a name attribute!");	
			}


			Regex valueRegex = new Regex(_valueExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			Match valueMatch = valueRegex.Match(htmlCode);
			if (valueMatch != null)
			{
				if (valueMatch.Value.Length > 0)
				{
					this.Value = valueMatch.Groups[2].Value;
				}
			}
		}

		public FormParameter(FormParameterType type, String name, String value)
		{
			Type = type;
			Name = name;
			Value = value;
		}
	}
}